// --- 模拟数据封装函数 ---
const getMockTasksData = () => {
    // 待接诊任务数据
    const waitingTasks = [
        { id: 101, name: '李先生', age: 35, gender: '男', type: '初诊', time: '10:00', waitTime: '15分钟', department: '正畸科' },
        { id: 102, name: '张女士', age: 28, gender: '女', type: '复诊', time: '10:30', waitTime: '5分钟', department: '种植科' },
        { id: 103, name: '赵先生', age: 50, gender: '男', type: '初诊', time: '11:00', waitTime: '0分钟', department: '牙周科' },
        { id: 104, name: '孙小姐', age: 22, gender: '女', type: '复诊', time: '11:15', waitTime: '10分钟', department: '修复科' },
        { id: 105, name: '周女士', age: 31, gender: '女', type: '初诊', time: '11:45', waitTime: '0分钟', department: '儿牙科' },
        { id: 106, name: '吴先生', age: 45, gender: '男', type: '复诊', time: '12:00', waitTime: '20分钟', department: '正畸科' },
        { id: 107, name: '郑先生', age: 38, gender: '男', type: '初诊', time: '14:00', waitTime: '0分钟', department: '口腔内科' }
    ];

    // 待复诊任务数据
    const followUpTasks = [
        { id: 201, name: '王女士', age: 28, gender: '女', lastTreatment: '根管治疗', suggestDate: '2025/12/05', status: '待确认' },
        { id: 202, name: '刘先生', age: 42, gender: '男', lastTreatment: '洁牙', suggestDate: '2026/01/10', status: '已预约' },
        { id: 203, name: '陈小姐', age: 19, gender: '女', lastTreatment: '拔智齿', suggestDate: '2025/12/20', status: '待确认' }
    ];

    // 待处理任务数据
    const pendingTasks = [
        { id: 301, source: '张先生 (在线咨询)', tag: '在线咨询', summary: '咨询智齿拔除的费用和流程...', receivedTime: '1小时前' },
        { id: 302, source: '系统通知', tag: '报告待批', summary: '患者X光片已上传，待医生审批', receivedTime: '20分钟前' }
    ];
    
    const completedTasks = []; 

    return {
        waitingTasks,
        followUpTasks,
        pendingTasks,
        completedTasks
    };
};

// --- Page 页面逻辑 ---
Page({
    data: {
        tabs: [], 
        currentTab: 0,
        todoCounts: {},
        waitingTasks: [],
        followUpTasks: [],
        pendingTasks: [],
        completedTasks: [],
        filter: 'today'
    },

    onLoad() {
        this.loadData();
    },

    /**
     * 核心函数：加载所有任务数据。
     */
    loadData() {
        const { 
            waitingTasks, 
            followUpTasks, 
            pendingTasks,
            completedTasks
        } = getMockTasksData();

        this.updateDataAndCounts({ waitingTasks, followUpTasks, pendingTasks, completedTasks });
    },
    
    /**
     * 统一的数据更新和计数计算函数。
     * @param {Object} newData 包含需要更新的任务列表对象，如 { waitingTasks: [...] }
     */
    updateDataAndCounts(newData) {
        // 确保使用最新的数据计算
        const waitingCount = newData.waitingTasks ? newData.waitingTasks.length : this.data.waitingTasks.length;
        const followUpCount = newData.followUpTasks ? newData.followUpTasks.length : this.data.followUpTasks.length;
        const pendingCount = newData.pendingTasks ? newData.pendingTasks.length : this.data.pendingTasks.length;
        const completedCount = newData.completedTasks ? newData.completedTasks.length : this.data.completedTasks.length;

        // 构造 Tab 结构
        const tabs = [
            { name: '待接诊', count: waitingCount },
            { name: '待复诊', count: followUpCount },
            { name: '待处理', count: pendingCount },
            { name: '已完成', count: completedCount }
        ];

        // 构造 setData 对象，进行一次性更新
        this.setData({
            todoCounts: {
                waiting: waitingCount,
                followUp: followUpCount,
                pending: pendingCount
            },
            tabs: tabs,
            ...newData // 传入最新的任务列表数据
        });
    },

    // --- 事件处理函数 ---

    // 切换 Tab
    switchTab(e) {
        const index = e.currentTarget.dataset.index;
        if (this.data.currentTab === index) return;
        
        this.setData({
            currentTab: index
        });
    },

    /**
     * 动作处理函数：立即接诊 (移除任务并更新计数)
     */
    startConsultation(e) {
        const taskId = e.currentTarget.dataset.id;
        
        // 1. 获取当前数组并创建副本
        let currentWaitingTasks = this.data.waitingTasks.slice();
        let currentCompletedTasks = this.data.completedTasks.slice();

        // 2. 查找任务并移除
        const taskIndex = currentWaitingTasks.findIndex(item => item.id == taskId);
        
        if (taskIndex !== -1) {
            const finishedTask = currentWaitingTasks.splice(taskIndex, 1)[0];
            
            // 3. 将完成的任务移到已完成列表
            currentCompletedTasks.unshift({ 
                ...finishedTask, 
                completedTime: new Date().toLocaleString(),
                type: finishedTask.type || '接诊'
            });

            // 4. 使用更新后的数组和计数
            this.updateDataAndCounts({ 
                waitingTasks: currentWaitingTasks,
                completedTasks: currentCompletedTasks 
            });

            wx.showToast({ title: `开始接诊: ${finishedTask.name}`, icon: 'success' });
            // TODO: 实际跳转到接诊/病历录入页面
        }
    },

    /**
     * 动作处理函数：安排预约 (移除任务并更新计数)
     */
    scheduleAppointment(e) {
        const taskId = e.currentTarget.dataset.id;
        
        // 1. 获取当前数组并创建副本
        let currentFollowUpTasks = this.data.followUpTasks.slice();
        
        // 2. 查找任务并移除
        const taskIndex = currentFollowUpTasks.findIndex(item => item.id == taskId);
        
        if (taskIndex !== -1) {
            // 注意：这里我们只移除，但没有移入 completedTasks，因为“安排预约”通常只是状态变更，但为了符合“移除并减数”的要求，我们将其移除
            // 若需更准确的业务逻辑，应将其状态改为“已预约”，而不是移除
            currentFollowUpTasks.splice(taskIndex, 1); 
            
            // 3. 更新数据和计数
            this.updateDataAndCounts({ followUpTasks: currentFollowUpTasks });

            wx.showToast({ title: `预约安排成功`, icon: 'success' });
            // TODO: 实际跳转到预约排班页面
        }
    },
    
    /**
     * 动作处理函数：处理待处理任务 (标记已读/立即处理) (移除任务并更新计数)
     */
    completeTask(e) {
        const taskId = e.currentTarget.dataset.id;
        const type = e.currentTarget.dataset.type; // 'read' 或 'handle'

        // 1. 获取当前数组并创建副本
        let currentPendingTasks = this.data.pendingTasks.slice();
        let currentCompletedTasks = this.data.completedTasks.slice();

        // 2. 查找任务并移除
        const taskIndex = currentPendingTasks.findIndex(item => item.id == taskId);
        
        if (taskIndex !== -1) {
            const finishedTask = currentPendingTasks.splice(taskIndex, 1)[0];
            
            // 3. 将完成的任务移到已完成列表
            currentCompletedTasks.unshift({ 
                ...finishedTask, 
                completedTime: new Date().toLocaleString(),
                type: finishedTask.tag || '通知处理'
            });

            // 4. 更新数据和计数
            this.updateDataAndCounts({ 
                pendingTasks: currentPendingTasks,
                completedTasks: currentCompletedTasks
            });

            wx.showToast({ title: type === 'read' ? `已标记已读` : `已处理`, icon: 'success' });
        }
    },
    
    // 动作处理函数：立即处理 (调用 completeTask 逻辑)
    handleTask(e) {
        this.completeTask(e);
        // TODO: 可在此添加跳转到咨询/审批页面逻辑
    },
    
    // 辅助动作函数 (保持不变)
    viewRecord(e) {
        const taskId = e.currentTarget.dataset.id;
        wx.showToast({ title: `查看任务${taskId}病历`, icon: 'none' });
    },
    contactPatient(e) {
        const taskId = e.currentTarget.dataset.id;
        wx.showToast({ title: `联系任务${taskId}患者`, icon: 'none' });
    },

    goBack() {
        wx.navigateBack({ delta: 1 });
    }
});